package com.xuecheng.ucenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.ucenter.mapper.XcMenuMapper;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.model.dto.AuthParamsDto;
import com.xuecheng.ucenter.model.dto.XcUserExt;
import com.xuecheng.ucenter.model.po.XcMenu;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName UserServiceImpl
 * @Description TODO
 * @Date 2023/6/27 13:57
 * @Version 1.0
 */
@Slf4j
@Component
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    XcUserMapper xcUserMapper;

    //注入 Spring 容器
    @Autowired
    ApplicationContext applicationcontext;

    @Autowired
    XcMenuMapper xcMenuMapper;


    /**
     * @param s AuthParamsDto 的 json 串
     * @return org.springframework.security.core.userdetails.UserDetails
     * @description 根据账号查询用户信息
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //将传入的 json 转成 AuthParamsDto 对象
        AuthParamsDto authParamsDto = null;
        try {
            //将认证参数转为 AuthParamsDto 类型
            authParamsDto = JSON.parseObject(s, AuthParamsDto.class);
        } catch (Exception e) {
            log.info("认证请求不符合项目要求: {}", s);
            throw new RuntimeException("请求认证参数不符合要求！");
        }

        //认证类型，有 password、wx...
        String authType = authParamsDto.getAuthType();
        //根据认证类型从 spring 容器取出指定的 bean(策略模式)
        String beanName = authType + "_authservice";
        AuthService authService = applicationcontext.getBean(beanName, AuthService.class);
        //调用统一的 execute 方法完成认证
        XcUserExt xcUserExt = authService.execute(authParamsDto);

        //封装 xcUserExt 为 UserDetails，并且根据其生成令牌
        UserDetails userDetails = getUserPrincipal(xcUserExt);
        return userDetails;
    }

    /**
     * @param xcUserExt 用户id，主键
     * @return com.xuecheng.ucenter.model.po.XcUser 用户信息
     * @description 查询用户信息
     */
    public UserDetails getUserPrincipal(XcUserExt xcUserExt) {
        //用户权限，如果不加报 Cannot pass a null GrantedAuthority collection
        String[] authorities = {"test"};
        //根据用户 id 查询用户的权限
        List<XcMenu> xcMenus = xcMenuMapper.selectPermissionByUserId(xcUserExt.getId());
        if (xcMenus.size() > 0) {
            //获取当前用户拥有的权限
            List<String> permissions = new ArrayList<>(xcMenus.size());
            xcMenus.forEach(m ->{
                permissions.add(m.getCode());
            });
            authorities = permissions.toArray(new String[0]);
        }
        String password = xcUserExt.getPassword();
        //为了安全在令牌中不放密码
        xcUserExt.setPassword(null);
        //将 xcUserExt 对象转 json
        String userString = JSON.toJSONString(xcUserExt);
        //创建 UserDetails 对象
        UserDetails userDetails = User.withUsername(userString).password(password).authorities(authorities).build();
        return userDetails;
    }


}

